<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑笔记 - 笔记系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        tailwind.config = { theme: { extend: { colors: { primary: '#4F46E5', secondary: '#F5F5F7', neutral: '#1F2937' }}}};
    </script>
</head>
<body class="bg-secondary min-h-screen">
<header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-pencil text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-neutral">编辑笔记</h1>
        </div>
        <a href="note.html" class="text-primary">返回列表</a>
    </div>
    </header>

<main class="container mx-auto px-4 py-8 max-w-3xl">
    <form id="noteForm" class="bg-white rounded-lg shadow-sm p-6 space-y-4">
        <div>
            <label class="block text-sm text-neutral/60 mb-1">标题</label>
            <input id="title" type="text" class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none">
        </div>
        <div>
            <label class="block text-sm text-neutral/60 mb-1">分类</label>
            <select id="categoryId" class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none">
                <option value="">未分类</option>
            </select>
        </div>
        <div>
            <label class="block text-sm text-neutral/60 mb-1">内容</label>
            <textarea id="content" rows="10" class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none"></textarea>
        </div>
        <div class="flex gap-3 justify-end">
            <button type="button" id="cancelBtn" class="px-4 py-2 rounded border border-gray-300 text-neutral hover:bg-gray-50">取消</button>
            <button type="submit" class="px-4 py-2 rounded bg-primary text-white hover:bg-primary/90">保存</button>
        </div>
    </form>
</main>

<script>
    const CURRENT_USER_ID = 1;
    const params = new URLSearchParams(location.search);
    const id = parseInt(params.get('id')) || null;

    document.addEventListener('DOMContentLoaded', () => {
        // 加载分类下拉
        axios.get('/categories', { params: { userId: CURRENT_USER_ID } })
            .then(res => {
                const sel = document.getElementById('categoryId');
                (Array.isArray(res.data) ? res.data : []).forEach(c => {
                    const opt = document.createElement('option');
                    opt.value = c.id;
                    opt.textContent = c.name;
                    sel.appendChild(opt);
                });
            })
            .catch(() => {});

        // 编辑场景加载详情
        if (id) {
            axios.get('/notes/detail', { params: { id, userId: CURRENT_USER_ID } })
                .then(res => {
                    const n = res.data;
                    if (!n || n.success === false) throw new Error('not_found');
                    document.getElementById('title').value = n.title || '';
                    document.getElementById('content').value = n.content || '';
                    document.getElementById('categoryId').value = n.categoryId || '';
                })
                .catch(err => {
                    console.error('加载笔记失败', err);
                    alert('笔记不存在或已删除');
                    location.href = 'note.html';
                });
        }

        // 表单提交
        document.getElementById('noteForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const title = document.getElementById('title').value.trim();
            const content = document.getElementById('content').value.trim();
            const categoryId = document.getElementById('categoryId').value.trim();
            if (!title) { alert('请输入标题'); return; }

            const form = new URLSearchParams();
            if (id) form.append('id', String(id));
            form.append('title', title);
            form.append('content', content);
            if (categoryId) form.append('categoryId', categoryId);
            form.append('userId', String(CURRENT_USER_ID));

            const url = id ? '/notes/update' : '/notes/create';
            axios.post(url, form, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
                .then(res => {
                    if (res.data && res.data.success === false) throw new Error('save_failed');
                    alert('保存成功');
                    location.href = 'note.html';
                })
                .catch(err => {
                    console.error('保存失败', err);
                    alert('保存失败');
                });
        });

        document.getElementById('cancelBtn').addEventListener('click', () => {
            history.back();
        });
    });
</script>
</body>
</html>